layui.define(['laytpl','form','base','../app/admin/menu-form'], function (exports) {
    var $=layui.jquery,layer=layui.layer,$setting=layui.config,$http=layui.http,$util=layui.common,laytpl = layui.laytpl,
        form = layui.form("#menu");
    var $tree = null,$table = $('#table'),$menuModal = $('#menu_modal'),$permissionModal = $('#permission_modal'),
        $form = $('#menu_modal form'),$form_clone=$form.clone(),$pform = $('#permission_modal form'),$pform_clone=$pform.clone(),$mSubmit = $('#menu_submit'),$pSubmit = $('#permission_submit'),
        menuSelNode = 0,menuSelNodeId = 0,permissionSelNode = {},permissionSelNodeId = 0,
        menuData=[];
    $('#menu-add').on('click', function () {
        // 表单清空
        $util.fn.clear($form);
        $form.attr('action',$setting.config.resource.menus.create);
        var parentId = $tree.get_parent(menuSelNode);
        if(menuSelNodeId>0 && parentId!='#' && parentId>=0 ) {
            layer.msg("不能添加三级菜单！", { icon: 2 });
        } else {
            var $parent = $menuModal.find("[name='parent']");
            $parent.parents(".form-group").show ();
            $parent.attr('disabled', true);
            if(menuSelNodeId === 0) {
                $parent.val("根节点");
            } else {
                $parent.val($tree.get_text(menuSelNode));
            }
            $form.find("[name='parentId']").val(menuSelNodeId);
            $menuModal.modal('show');
        }
    });
    $('#menu-del').on('click', function () {
        if (menuSelNodeId >0) {
            var resourceId = menuSelNodeId;
            layer.confirm('确认删除此条数据吗？', {
                icon: 2,
                title: ['提示', 'font-size:15px;text-align:left;padding-left: 10px;'],
                btn: ['确定', '取消'],          //按钮
                skin: 'layui-layer-molv'
            }, function() {
                $http.post($setting.config.resource.menus.del, {resourceId:resourceId}).send(function (data) {
                    if (data.code == '0') {
                        loadTree();
                        layer.msg("删除成功！", { icon: 1 });
                    } else {
                        layer.msg("删除失败：" + data.message, { icon: 2 });
                    }
                });
            }, function() {
                layer.closeAll('dialog');
            });
        } else {
            layer.msg("请选中一个菜单修改！", { icon: 2 });
        }
    });
    $('#menu-edit').on('click', function () {
        if (menuSelNodeId >0) {
            //$util.fn.clear($form);
            var resource = getData(menuSelNodeId);
            //var $parent = $menuModal.find("[name='parent']");
            $form_clone.find("[name='parent']").parents(".form-group").hide();
            $form_clone.find("[name='id']").val(menuSelNodeId);
            $form_clone.find("[name='parentId']").val(resource.parentId);
            //$form_clone.attr('action',$setting.config.resource.menus.update);
            laytpl($form_clone.html()).render(resource, function (html) {
                $form.html(html);
                $form.attr("action",$setting.config.resource.menus.update)
            });
            $menuModal.modal('show');
        } else {
            layer.msg("请选中一个菜单修改！", { icon: 2 });
        }
    });
    $('#permission-add').on('click', function () {
        if (menuSelNodeId >0) {
            // 表单清空
            $pform.resetForm();
            $pform.find("[name='parentId']").val(menuSelNodeId);
            $pform.attr('action',$setting.config.resource.menus.create);
            $permissionModal.modal('show');
        } else {
            layer.msg("请选中一个菜单，才能添加按钮权限！", { icon: 2 });
        }
    });
    $('#permission-edit').on('click', function () {
        if (permissionSelNodeId >0) {
            $pform.resetForm();
            $pform.find("[name='id']").val(permissionSelNodeId);
            $pform.find("[name='parentId']").val(permissionSelNode.parentId);
            $pform.find("[name='text']").val(permissionSelNode.text);
            $pform.find("[name='permission']").val(permissionSelNode.permission);
            $pform.attr('action',$setting.config.resource.menus.update);
            $permissionModal.modal('show');
        } else {
            layer.msg("请选中一个权限修改！", { icon: 2 });
        }
    });
    $('#permission-del').on('click', function () {
        if (permissionSelNodeId >0) {
            var resourceId = permissionSelNodeId;
            layer.confirm('确认删除此条数据吗？', {
                icon: 2,
                title: ['提示', 'font-size:15px;text-align:left;padding-left: 10px;'],
                btn: ['确定', '取消'],          //按钮
                skin: 'layui-layer-molv'
            }, function() {
                $http.post($setting.config.resource.menus.del, {resourceId:resourceId}).send(function (data) {
                    if (data.code == '0') {
                        $table.bootstrapTable('refresh', { silent: true });
                        layer.msg("删除成功！", { icon: 1 });
                    } else {
                        layer.msg("删除失败：" + data.message, { icon: 2 });
                    }
                });
            }, function() {
                layer.closeAll('dialog');
            });
        } else {
            layer.msg("请选中一个菜单修改！", { icon: 2 });
        }
    });
    // 加载菜单树
    var loadTree = function() {
        $http.get($setting.config.resource.menus.list, {}).send(function (data) {
            menuData = data.data;
            var data = menuData;
            if ($tree) {
                $tree.settings.core.data=data;
                $tree.refresh();
            } else {
                $tree = $("#menuTree").jstree({'core': {'data':data}}).jstree();
                $('#menuTree').on("changed.jstree", function (e, data) {
                    menuSelNode = data.selected;
                    if (menuSelNode && menuSelNode.length==1) {
                        menuSelNodeId = menuSelNode[0];
                        $table.bootstrapTable('refresh', { silent: true });
                    }
                });
            }
        });
    };
    // 初始化表格
    $table.bootstrapTable({
        url: $setting.getUri() + $setting.config.resource.permission,
        dataType: "json",
        ajaxOptions: {
            xhrFields: {        //跨域
                withCredentials: true
            },
            crossDomain: true
        },
        pagination: false,
        idField: 'id',
        clickToSelect:true,
        singleSelect:true,
        dataField: 'data',
        columns: [{
            field: 'id',
            align: 'center',
            title: 'id'
        }, {
            field: 'parentId',
            align: 'center',
            title: 'parentId'
        },{
            field: 'text',
            align: 'center',
            title: '名称'
        }, {
            field: 'permission',
            align: 'center',
            title: '表达式'
        }/*, {
            field: 'status',
            align: 'center',
            title: '状态',
            formatter: function (value, row) {
                if (value == 0) {
                    return '无效';
                } else if (value == 1) {
                    return '有效';
                }
            }
        }*/],
        queryParams: function (params) {
            var query = {
                parentId: menuSelNodeId,
                pageIndex: params.pageNumber,
                pageSize: params.limit //页面大小
            };
            return query;
        },
        onClickRow: function (row, $element) {
            permissionSelNodeId = row.id;
            permissionSelNode = row;
            $element.siblings().css('background-color','white');
            $element.css("background-color", "rgb(243, 247, 249)");
        }
    });
    $table.bootstrapTable('hideColumn', 'id');
    $table.bootstrapTable('hideColumn', 'parentId');
    var getData = function(resourceId) {// 目前只会有二级菜单
        for (var i in menuData) {
            var children = menuData[i].children;
            if(menuData[i].id == resourceId) {
                return menuData[i];
            } else if(children.length>0) {
                for (var j in children) {
                    if(children[j].id == resourceId) {
                        return children[j];
                    }
                }
            }
        }
    };
    //　表单提交
    form.on('submit(menu)', function(data){
        var action = $form.attr('action');
        var formData = data.field;
        $http.post(action, formData).send(function (obj) {
            if (obj.code == '0') {
                loadTree();
                $menuModal.modal('hide');
                layer.msg("保存成功！", { icon: 1 });
            } else {
                layer.msg("保存失败：" + obj.message, { icon: 2 });
            }
        });
    });
    form.on('submit(permission)', function(data){
        var action = $pform.attr('action');
        var formData = data.field;
        $http.post(action, formData).send(function (obj) {
            if (obj.code == '0') {
                $table.bootstrapTable('refresh', { silent: true });
                $permissionModal.modal('hide');
                layer.msg("保存成功！", { icon: 1 });
            } else {
                layer.msg("保存失败：" + obj.message, { icon: 2 });
            }
        });
    });
    // 加载树
    loadTree();
    exports('../app/admin/menu', {});
});